#pragma once
#include <iostream>
#include <sys/epoll.h>
#include "Log.hpp"
#include "Common.hpp"
using namespace LogModule;
namespace EpollerModule
{
    class Epoller
    {
    public:
        Epoller()
            : _epfd(-1)
        {
        }
        void Init()
        {
            _epfd = epoll_create(1024);
            if (_epfd < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_create error";
                exit(EPOLL_CREATE_ERR);
            }
            LOG(LogLevel::INFO) << "epoll_create success" << "epfd=" << _epfd;
        }
        int Wait(struct epoll_event events[], int maxevents, int timeout)
        {
            int n = epoll_wait(_epfd, events, maxevents, timeout);
            if (n < 0)
            {
                LOG(LogLevel::WARING) << "epoll_wait error";
            }
            return n;
        }
        void Add(int fd, uint32_t events)
        {
            Ctrl(fd, events, EPOLL_CTL_ADD);
        }
        void Update(int fd, uint32_t events)
        {
            Ctrl(fd, events, EPOLL_CTL_MOD);
        }
        void Delete(int fd)
        {
            int n=epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, NULL);
        }
        void Ctrl(int fd, uint32_t events, int flag)
        {
            struct epoll_event event;
            event.events = events;
            event.data.fd = fd;
            int n = epoll_ctl(_epfd, flag, fd, &event);
            if (n < 0)
            {
                LOG(LogLevel::WARING) << "epoll_ctl error";
            }
        }

        ~Epoller() {}

    private:
        int _epfd;
    };
}